<?php
require_once("lib.php");
header('Content-Type: application/json');
if (isset($_POST["m"]) && trim($_POST["m"]) != "" ) {
	$multiTracks = json_decode(base64_decode($_POST["m"]), true);
	$tracks = $multiTracks["multitracks"];

    $trackData = Array();
	foreach ($tracks as $trackID) {
        $points = Array();
		$stmt = $db->prepare("SELECT id as trackID, trackName, userDescr, tableName, UNIX_TIMESTAMP(trackDate) as trackDate FROM track_tables_info WHERE id = :trackID");
        if ($stmt->execute(array("trackID" => $trackID))) {
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
		    $trackName = $row["trackName"];
    		$tableName = $row["tableName"];
        } else {
            echo json_encode(array("status" => "error", "message" => "failed to query track table name"));
            exit();
        }

		$stmt = $db->prepare("SELECT Y(SHAPE) AS latitude, X(SHAPE) AS longitude, UNIX_TIMESTAMP(time) AS trackPointDate, ele AS elevation FROM $tableName ORDER BY time");
		$first = true;
        if ($stmt->execute()) {
            while ($row = $stmt->fetch()) {
                $points[] = array("lat" => $row["latitude"], "lon" => $row["longitude"]);
                if ($first) {
                    $startLat = $row["latitude"];
                    $startLon = $row["longitude"];
                    $startDate = sprintf("START %s: %s (%f, %f)", date("c", $row["trackPointDate"]), $trackName, $startLat, $startLon);
                    $startEle = sprintf("%.2f", $row["elevation"] * FEET_PER_METER);
                    $first = false;
                }
            }
            $endLat = $row["latitude"];
            $endLon = $row["longitude"];
            $endDate = sprintf("END %s: %s (%f, %f)", date("c", $row["trackPointDate"]), $trackName, $endLat, $endLon);
            $endEle = sprintf("%.2f", $row["elevation"] * FEET_PER_METER);			
            $trackData[] = array("trackID" => $trackID, "trackData" => array(
                    "points" => $points,
                    "startLat" => $startLat, 
                    "startLon" => $startLon,
                    "startDate" => $startDate,
                    "startElevation" => $startEle,
                    "endLat" => $endLat, 
                    "endLon" => $endLon,
                    "endDate" => $endDate,
                    "endElevation" => $endEle));
        } else {
            echo json_encode(array("status" => "error", "message" => "failed to query points from track table"));
        }
    }
    echo json_encode(array("status" => "success", "mapType" => "tracks", "startLat" => $startLat, "startLon" => $startLon, "data" => $trackData));
} elseif (isset($_POST["m"]) && trim($_POST["m"]) == "") {
    echo json_encode(array("status" => "success", "mapType" => "centerOnPoint", "startLat" => 35.5628, "startLon" => -83.4986));
} else {
	echo "missing trackID param!";
	exit;
}

?>
